﻿using ELS.Models;
using ELS.Services;
using FluentValidation;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using MudBlazor;
using System.Collections.ObjectModel;
using static MudBlazor.CategoryTypes;

namespace ELS.Components.Pages
{
	public partial class TopicManger
	{
		[Inject] ISnackbar Snackbar { get; set; }

		MudForm form;

		QuestionFluentValidator questionValidator = new QuestionFluentValidator();

		List<Question> questions;

		Question currentQuestion = new();

		IReadOnlyCollection<int> selectedIDs;

		QuestionService _questionService = new QuestionService();
		protected override async Task OnInitializedAsync()
		{
			await Task.Delay(100); // 等待数据加载完毕
			var result = await _questionService.GetAllQuestions();
			questions = result.ToList();
			if (questions.Any())
			{
				UpdateCurrentQuestion(questions[0].Id); // 初始化时选中第一项
			}
		}

		private async Task Submit()
		{
			await form.Validate();

			if (form.IsValid)
			{
				Snackbar.Add($"ID：{currentQuestion.Id} 题目已保存!");
				_questionService.UpdateQuestion(currentQuestion);
			}
		}

		private async void AddQuestion()
		{
			questions.Add(new Question()
			{
				Title = "新题目",
				Answer1 = "答案一",
				Answer2 = "答案二",
				Answer3 = "答案三",
				Answer4 = "答案四",
				CurentAnswerIndex = 1,
				Category = "其他"
			});

			_questionService.AddQuestion(questions.Last());
			var result = await _questionService.GetAllQuestions();
			questions = result.ToList();
			UpdateCurrentQuestion(questions.Last().Id); // 初始化时选中第一项
			StateHasChanged();
		}

		[Inject] IDialogService DialogService { get; set; }

		private async Task DeleteQuestion()
		{
			var dialog = await DialogService.ShowAsync<SimpleDialog>($"确认删除{selectedIDs.Count}条记录?");
			var result = await dialog.Result;

			if (result.Canceled)
			{
				return;
			}

			foreach (var id in selectedIDs)
			{
				_questionService.DeleteQuestion(id);
				questions.Remove(questions.FirstOrDefault(q => q.Id == id));
			}
			if (questions.Any())
			{
				UpdateCurrentQuestion(questions[0].Id); // 初始化时选中第一项
			}
			StateHasChanged();
		}

		public void UpdateCurrentQuestion(int id)
		{
			currentQuestion = questions.FirstOrDefault(q => q.Id == id);
			selectedIDs = new ReadOnlyCollection<int>(new List<int>() { id });
		}

		public void PreviousQuestion()
		{
			var targetIndex = questions.IndexOf(currentQuestion) - 1;
			if (targetIndex < 0)
			{
				targetIndex = questions.Count - 1;
			}
			UpdateCurrentQuestion(questions[targetIndex].Id);
			StateHasChanged();
		}

		public void NextQuestion()
		{
			var targetIndex = questions.IndexOf(currentQuestion) + 1;
			if (targetIndex >= questions.Count)
			{
				targetIndex = 0;
			}
			UpdateCurrentQuestion(questions[targetIndex].Id);
			StateHasChanged();
		}

		bool _visible;
		private async Task UploadFiles(InputFileChangeEventArgs file)
		{
			//TODO upload the files to the server
			var files = file.GetMultipleFiles();
			var f = files.First();
			var name = f.Name;
			var content = f.OpenReadStream();
			// 指定文件保存的路径
			if (!Directory.Exists("./wwwroot/temp"))
			{
				Directory.CreateDirectory("./wwwroot/temp");
			}
			_visible = true;
			string filePath = Path.Combine("./wwwroot/temp", name);
			// 使用 FileStream 异步将内容写入文件
			using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.Asynchronous))
			{
				await content.CopyToAsync(fileStream); // 使用异步方法复制流的内容
			}

			// 读取文件内容
			await ReadFile(filePath);
			_visible = false;
			Snackbar.Add("上传成功!");
			StateHasChanged();
		}

		private async Task ReadFile(string filePath)
		{
			await Task.Delay(3000);
		}
	}
}
